package cn.qf.shop.service.impl;

import cn.qf.shop.mapper.CartMapper;
import cn.qf.shop.mapper.GoodsMapper;
import cn.qf.shop.pojo.entity.Cart;
import cn.qf.shop.pojo.entity.Goods;
import cn.qf.shop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public List<Cart> selectCartByUserId(Long userId) {
        List<Cart> cart = cartMapper.selectCartByUserId(userId);
        if(cart.size()==0){
            throw new RuntimeException("该用户购物车没商品");
        }
        return cart;
    }

    @Override
    public int insertCart(Integer uId, Integer gId) {
        Cart cart = new Cart();
        Goods goods = goodsMapper.selectGoodsById(gId);
        BigDecimal getgPrice = goods.getgPrice();
        cart.setuId(uId);
        cart.setgId(gId);
        cart.setcCount(getgPrice);
        cart.setcNum(1);
        int i = cartMapper.insertCart(cart);
        System.out.println("CartService"+i);
        return i;
    }

    @Override
    public int deleteCartByCid(Integer cId) {
        int i = cartMapper.deleteCartByCid(cId);
        if(i==0){
            throw new RuntimeException("cid不存在");
        }
        return i;
    }

    @Override
    public int clearCart(Integer userId) {
        int i = cartMapper.clearCart(userId);
        if(i==0){
            throw new RuntimeException("该用户购物车没有数据");
        }
        return i;
    }

    @Override
    public int updateCartByCid(Integer cId, Integer cNum, BigDecimal gPrice1) {
        BigDecimal bigCnum = new BigDecimal(cNum);
        BigDecimal cCount = bigCnum.multiply(gPrice1);
        int i = cartMapper.updateCartByCid(cId,cNum,cCount);
        if(i==0){
            throw new RuntimeException("cId不存在");
        }
        return i;
    }

    @Override
    public Cart selectCartByCid(Integer uId, Integer gId) {
         Cart cart = cartMapper.selectCartByCid(uId,gId);

         return cart;
    }
}
